import axios, {
    type AxiosResponse,
    type InternalAxiosRequestConfig,
  } from "axios";
  import {useTokenStore} from "../store/tokenStore";
  
  export const baseURL = "http://localhost:5000";

  
  const instance = axios.create({
    baseURL: baseURL,
    timeout: 60000,
  });
  
  instance.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
      if (config.headers["Content-Type"] == null) {
        config.headers["Content-Type"] = "application/json;charset=utf-8";
      }
      
      const tokenStore = useTokenStore();
      const token = tokenStore.getToken();
      if (token) {
        config.headers["Authorization"] = `Bearer ${token}`;
      }
      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
  );
  
  instance.interceptors.response.use(
    (response: AxiosResponse) => {
      return response.data;
    },
    (error) => {
      return Promise.reject(error);
    }
  );
  
  // 封装 GET 请求
  export const get = <T>(url: string, params?: any): Promise<AxiosResponse<T, any>> => {
    return instance.get<T>(url, { params });
  };
  
  // 封装 POST 请求
  export const post = <T>(url: string, data?: any): Promise<AxiosResponse<T, any>> => {
    return instance.post<T>(url, data);
  };
  
  export const postUploadFile = <T>(url:string,file:File, data?: any): Promise<AxiosResponse<T, any>> =>{
    const formData = new FormData();
    formData.append('file', file);
    if (data) {
      Object.keys(data).forEach(key => {
        formData.append(key, data[key]);
      });
    }
    return instance.post<T>(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  }
  
  // 封装文件上传请求（支持文件列表和额外参数）
  export const postUploadFiles = <T>(url: string, files: File[], data?: any): Promise<AxiosResponse<T, any>> => {
      const formData = new FormData();
      files.forEach((file, index) => {
        formData.append(`files`, file);
      });
      if (data) {
        Object.keys(data).forEach(key => {
          formData.append(key, data[key]);
        });
      }
      return instance.post<T>(url, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
    };
  
    export default instance;
  